package main

import (
	"context"
	"data-center/api/http/router"
	"data-center/config"
	"data-center/pkg/database/mongodb"
	"data-center/pkg/database/mysql"
	"data-center/pkg/queue"
	_ "data-center/pkg/queue/kafka" // 添加这行导入
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	// 加载配置
	cfg, err := config.LoadConfig("")
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// 初始化日志
	// logger.Init(cfg.Log)

	// 初始化MySQL数据库
	mysqlDB, err := mysql.NewDB(mysql.Config{
		Host:     cfg.MySQL.Host,
		Port:     cfg.MySQL.Port,
		Username: cfg.MySQL.Username,
		Password: cfg.MySQL.Password,
		Database: cfg.MySQL.Database,
		Params:   cfg.MySQL.Params,
	})
	if err != nil {
		log.Fatalf("Failed to initialize MySQL: %v", err)
	}

	// 获取底层sqlDB以便后续关闭连接
	sqlDB, err := mysqlDB.DB()
	if err != nil {
		log.Fatalf("Failed to get SQL DB: %v", err)
	}
	defer sqlDB.Close()

	// 初始化MongoDB
	// 在初始化 MongoDB 后
	mongoClient, err := mongodb.NewClient(mongodb.Config{
		URI: cfg.MongoDB.URI,
		Databases: map[string]string{
			"news":      cfg.MongoDB.Databases.News,
			"ecommerce": cfg.MongoDB.Databases.Ecommerce,
			"social":    cfg.MongoDB.Databases.Social,
		},
	})
	if err != nil {
		log.Fatalf("Failed to initialize MongoDB: %v", err)
	}
	defer func() {
		if err := mongoClient.Close(context.Background()); err != nil {
			log.Printf("Error closing MongoDB connection: %v", err)
		}
	}()

	// 初始化队列生产者
	producer, err := queue.NewProducer(cfg.Queue)
	if err != nil {
		log.Fatalf("Failed to initialize queue producer: %v", err)
	}
	defer producer.Close()

	// 设置Gin模式
	if cfg.App.Mode == "production" {
		gin.SetMode(gin.ReleaseMode)
	}

	// 创建Gin引擎
	r := gin.Default()

	// 注册路由
	router.SetupRouter(r, mysqlDB, mongoClient, producer)

	// 创建HTTP服务器
	srv := &http.Server{
		Addr:    fmt.Sprintf(":%d", cfg.App.Port),
		Handler: r,
	}

	// 启动HTTP服务器
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Failed to start server: %v", err)
		}
	}()

	// 等待中断信号优雅关闭服务器
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutting down server...")

	// 设置关闭超时时间
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 关闭服务器
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalf("Server forced to shutdown: %v", err)
	}

	log.Println("Server exiting")
}
